  //获取所有方块保存为数组，Array.from转为数组
 let squares = Array.from(document.querySelectorAll('.grid div'))
    
 const width = 10
 let score = 0;
 let grid = document.querySelector('.grid')

 let timerId=0

  //绘制变化的方块
  const Tetromion1 = [
    [1,2,width+1,width*2+1],
    [width,width+1,width+2,width*2+2],
    [1,width+1,width*2,width*2+1],
    [width,width*2,width*2+1,width*2+2]
]

const Tetromion2 = [
    [width+1,width+2,width*2,width*2+1],
    [0,width,width+1,width*2+1],
    [width+1,width+2,width*2,width*2+1],
    [0,width,width+1,width*2+1]

]

const Tetromion3 = [
    [1,width,width+1,width+2],
    [1,width+1,width+2,width*2+1],
    [width,width+1,width+2,width*2+1],
    [1,width,width+1,width*2+1]

]

const Tetromion4 = [
    [0,1,width,width+1],
    [0,1,width,width+1],
    [0,1,width,width+1],
    [0,1,width,width+1]

]

const Tetromion5 = [
    [1,width+1,width*2+1,width*3+1],
    [width,width+1,width+2,width+3],
    [1,width+1,width*2+1,width*3+1],
    [width,width+1,width+2,width+3]

]

const Tetromions = [
    Tetromion1,Tetromion2,Tetromion3,Tetromion4,Tetromion5
]

 //方块出现位置
 let currentPosition = 4
 //Math.random方法随机生成一个方块,Math.floor()向下取整
 let ran=Math.floor(Math.random()*Tetromions.length)
 //第几种形式的方块
 let currentRotation = 0

 //生成的方块坐标
 let current = Tetromions[ran][currentRotation]

 let nextRandom = 0

 //在侧边小方格中展示下一个形状
const displaySquares =Array.from(document.querySelectorAll('.mini-grid div')) 
const displayWidth = 4
let displayIndex = 0

//对应的几种不同方块
const upNextTetrominoes = [
    [1,displayWidth+1,displayWidth*2+1,2],
    [0,displayWidth,displayWidth+1,displayWidth*2+1],
    [1,displayWidth,displayWidth+1,displayWidth+2],
    [0,1,displayWidth,displayWidth+1],
    [1,displayWidth+1,displayWidth*2+1,displayWidth*3+1]
]

  
 //绘制选中方块的样式
  const draw =function () {
    current.forEach(index => {
        squares[currentPosition+ index].classList.add('tetromino')           
    });
  }

//移除上一秒的css样式
const undraw = function() {
    current.forEach(index => {
        squares[currentPosition+ index].classList.remove('tetromino')            
    });
}

//方块移动函数
let moveDown = function(){
    undraw()    
    currentPosition +=10 
    draw()    
    freeze()     
}

//向左移动函数
const moveLeft = () =>{
    undraw()
    const isAtLeft = current.some(v => (currentPosition + v)%width == 0)
    
    if(!isAtLeft)
        currentPosition -= 1
    if(current.some(v => squares[currentPosition + v].classList.contains('taken')))
        currentPosition +=1

    draw()
}


//向右移动函数
const moveRight = () =>{
    undraw()
    const isAtright = current.some(v => (currentPosition + v)%width == 9)
    
    if(!isAtright)
        currentPosition += 1
    if(current.some(v => squares[currentPosition + v].classList.contains('taken')))
        currentPosition -= 1

    draw()
}

//旋转形状
const rotate = () =>{
    undraw()
    currentRotation++
    if(currentRotation === current.length ){
        currentRotation = 0
    }
    current = Tetromions[ran][currentRotation]
    draw()
}

  
//方块到底停止的方法
const freeze = ()=>{
    //数组的some方法。判断下一行方块是否为taken，如果taken则停止
    if(current.some(v => squares[currentPosition + v +width].classList.contains('taken'))){
        log("到达底部")
        //添加taken样式作为当前底部
        current.forEach(v => squares[currentPosition + v ].classList.add('taken'))
        //重新开始一轮
        ran=nextRandom
        nextRandom=Math.floor(Math.random()*Tetromions.length)
        current = Tetromions[ran][currentRotation]
        currentPosition=4 
        displayShape()
        draw()
        gameOver()
        addScore()
    }
}

//在小方格中绘制下一次的方块形状
const displayShape = () =>{
    displaySquares.forEach(square =>{
        square.classList.remove('tetromino')
    })
    
    upNextTetrominoes[nextRandom].forEach( index => {
        displaySquares[displayIndex+index].classList.add('tetromino')
    })
}


//分数以及消除函数
const addScore = () =>{
   
    for(let i = 0;i < 199;i +=10){
        let row=[i,i+1,i+2,i+3,i+4,i+5,i+6,i+7,i+8,i+9]

        //数组的every方法，检查所有元素，有一个不符合就返回false，否则返回true
        if(row.every(index =>(squares[index].classList.contains('taken')))){
            score +=10
            e('#score').innerHTML = score
            row.forEach(index =>{
                squares[index].classList.remove('taken')
                 squares[index].classList.remove('tetromino')
            })
           const squaresRemove = squares.splice(i,width)
           squares = squaresRemove.concat(squares)
           squares.forEach(v => e('.grid').appendChild(v))
        }
    }
}


//游戏结束函数
const gameOver = () =>{
    if(current.some( index => squares[currentPosition+index].classList.contains('taken'))){
       alert(`游戏结束你的得分是${score}`)
        clearInterval(timerId)
    }
}

//点击按钮出发定时器开始游戏
const bindStart=() =>{
    e('button').addEventListener('click',function(){
    
       if(timerId){
            //取消该定时器
            clearInterval(timerId)
            timerId = null
       }else{
            draw()
            timerId = setInterval(moveDown,1000); 
            nextRandom=Math.floor(Math.random()*Tetromions.length)
            displayShape()
       }
         
    })
}

const bindKey = () =>{
    bindEvent(document, 'keydown',(e) =>{
        if(e.keyCode === 37){
            //向左移动
            moveLeft()
        }else if (e.keyCode === 38){
            //旋转形状
            rotate()
        }else if (e.keyCode === 39){
            //向右移动
            moveRight()
        }else if (e.keyCode === 40){
            //向下移动
            moveDown()
        }
    })
}

const bindEvents= () =>{
    bindStart()
    bindKey()
}



const main = () =>{
    bindEvents()
}

main()

